package io.yyxx.boot.util.map;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SignatureHelper {

  /**
   * 签名值计算。
   *
   * @param bizSecret 业务密钥。
   * @param argValues 待签名的业务参数，按接口指定的参数顺序传值。
   * @return bizSign签名值。
   */
  public static String calcSign(String bizSecret, String[] argValues) {
    StringBuilder sb = new StringBuilder();
    for (String argValue : argValues) {
      if (argValue == null || "".equals(argValue)) {
        continue;
      }
      sb.append(argValue);
    }
    sb.append("@").append(bizSecret);
    try {
      byte[] bys = URLEncoder.encode(sb.toString(), StandardCharsets.UTF_8.name())
          .getBytes(StandardCharsets.UTF_8);
      MessageDigest md = MessageDigest.getInstance("MD5");
      return encodeHex(md.digest(bys));
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    }
  }

  private static final char[] DIGITS_UPPER = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8',
      '9', 'A', 'B', 'C', 'D', 'E', 'F'};

  public static String encodeHex(byte[] bytes) {
    StringBuilder sb = new StringBuilder(2 * bytes.length);
    for (byte b : bytes) {
      sb.append(DIGITS_UPPER[(b >> 4) & 0xf]).append(DIGITS_UPPER[b & 0xf]);
    }
    return sb.toString();
  }
}
